import axios from 'axios'
import { message } from '@/utils/message'
import store from '@/store'
import { getToken, getYecaiUserId, setYecaiUserId, setYecaiEncriptedUserId, getYecaiEncriptedUserId, setIsInYecaiOA, getIsInYecaiOA } from '@/utils/auth'
import define from '@/utils/define'
import context from '@/main'
import jnpf from '@/utils/jnpf'
import JSEncrypt from "jsencrypt";
import { rsaPublicKey } from '../publicKeyForEncrypt'

// 获取/验证 业财OA带过的登陆人id并加密
export function getEncryptUserId() {
  const yecaiUserId = jnpf.getYecaiUserIdFromOA();

  const oldUserId = getYecaiUserId();
  if (yecaiUserId) {
    if (yecaiUserId !== oldUserId) {
      const encryptor = new JSEncrypt();
      encryptor.setPublicKey(rsaPublicKey);
      const resKeyword = encryptor.encrypt(`yecai-${yecaiUserId}`)
      setYecaiUserId(yecaiUserId);
      setYecaiEncriptedUserId(resKeyword)
      return resKeyword;
    }
    const oldEncryptedId = getYecaiEncriptedUserId();
    return oldEncryptedId
  } else {
    setIsInYecaiOA(false)
    setYecaiUserId('')
    setYecaiEncriptedUserId('')
    return
  }
}

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: false, // send cookies when cross-domain requests
  timeout: define.timeout, // request timeout
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (config.url.indexOf('http') > -1) config.baseURL = ''
    // 部分接口timeout时间单独处理
    if (config.url.indexOf('SynThirdInfo') > -1 || config.url.indexOf('extend/Email/Receive') > -1 ||
      config.url.indexOf('Permission/Authority/Data') > -1 || config.url.indexOf('DataSync/Actions/Execute') > -1) {
      config.timeout = 100000
    }
    // do something before request is sent
    config.headers['jnpf-origin'] = 'pc'

    // 业财OA登录不需要token,只需要给加密后的用户手机号
    const userIdFromOA = getEncryptUserId();
    if (userIdFromOA) {
      config.headers['ENCRYPTION-KEY'] = userIdFromOA
      if (getToken()) {
        window.localStorage.removeItem('jnpf_token'); // 清除token，防止浏览器tab合并策略导致的登录信息共享
      }
      if (config.headers['Authorization']) {
        delete config.headers['Authorization']
      }
    } else if (store.getters.token) {
      config.headers['Authorization'] = getToken()
    }
    
    if (config.method == 'get') {
      config.params = config.data
      delete config.data
    }
    let timestamp = Date.parse(new Date()) / 1000
    if (config.url.indexOf('?') > -1) {
      config.url += `&n=${timestamp}`
    } else {
      config.url += `?n=${timestamp}`
    }
    return config
  },
  error => {
    // do something with request error
    if (process.env.NODE_ENV !== 'production') {
      console.log(error) // for debug
    }
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    let res = response.data
    let config = response.config
    let url = config.url
    // 特殊接口处理
    if (url.indexOf('/Base/DataSource/Actions/Test') > -1 || (url.indexOf('OnlineDev') > -1 && url.indexOf('Config') > -1 || (url.indexOf('api/visualdev/Porta') > -1 && url.indexOf('auth') > -1))) return res
    if (![200, 0].includes(res.code)) {
      message({
        message: res.msg || '请求出错，请重试',
        type: 'error',
        duration: 1500,
        onClose: () => {
          if (url.indexOf('/api/oauth/Login') < 0 && url.indexOf('/api/oauth/LockScreen') < 0 && (res.code === 600 || res.code === 601 || res.code === 602)) {
            // 600：登录过期,请重新登录  601: 您的帐号在其他地方已登录,被强制踢出 602: Token验证失败
            store.dispatch('user/resetToken').then(() => {
              if (window.location.pathname.indexOf('login') > -1) return
              // setTimeout(() => { location.reload() }, 100);
              context.$router.push(`/login`)
            })
          }
        }
      })
      if (url.indexOf('/api/oauth/Login') > -1) return Promise.reject(res)
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    if (process.env.NODE_ENV !== 'production') {
      console.log(error) // for debug
    }
    message({
      message: '请求出错，请重试',
      type: 'error',
      duration: 1500
    })
    return Promise.reject(error)
  }
)

export default service